#include <stm32f10x_flash.h>
#include <stm32f10x_rcc.h>
#include <stm32f10x_gpio.h>
#include <stm32f10x.h>
#include <stm32f10x_spi.h>
#include <misc.h>
#include "init.h"
#include "radio.h"

SPI_InitTypeDef SPI_InitStructure;
GPIO_InitTypeDef GPIO_Conf;


void RCC_Conf (void)
{
  ErrorStatus HSEStartUpStatus;

  RCC_DeInit();
  RCC_HSEConfig (RCC_HSE_ON);
  HSEStartUpStatus = RCC_WaitForHSEStartUp();
  if (HSEStartUpStatus == SUCCESS)
    {
      FLASH_PrefetchBufferCmd (FLASH_PrefetchBuffer_Enable);
      FLASH_SetLatency (FLASH_Latency_2);
      RCC_HCLKConfig (RCC_SYSCLK_Div4);
      RCC_PCLK2Config (RCC_HCLK_Div4);
      RCC_PCLK1Config (RCC_HCLK_Div2);
      RCC_SYSCLKConfig (RCC_SYSCLKSource_HSE);
      while (RCC_GetSYSCLKSource() != 0x04) continue;
    }
}


void init_port (void)
{
  RCC_APB2PeriphClockCmd (RCC_APB2Periph_GPIOA, ENABLE);
  RCC_APB2PeriphClockCmd (RCC_APB2Periph_GPIOB, ENABLE);
  RCC_APB2PeriphClockCmd (RCC_APB2Periph_GPIOC, ENABLE);

  // thinking this is the activate button
  GPIO_Conf.GPIO_Pin = GPIO_Pin_12;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOA, &GPIO_Conf);
  GPIO_ResetBits (GPIOA, GPIO_Pin_12); // gnd one side of the button

  // onboard LEDs
  GPIO_Conf.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOB, &GPIO_Conf);

  // DHT11
  GPIO_Conf.GPIO_Pin = GPIO_Pin_10;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOB, &GPIO_Conf);

  // SPI2_SCK & SPI2_MOSI
  GPIO_Conf.GPIO_Pin = GPIO_Pin_13 | radioSDIpin;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOB, &GPIO_Conf);

  // SPI2_MISO
  GPIO_Conf.GPIO_Pin = GPIO_Pin_14;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init (GPIOB, &GPIO_Conf);

  // radioNSELpin
  GPIO_Conf.GPIO_Pin = radioNSELpin;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOC,&GPIO_Conf);

  spi_init();
}


void spi_init (void)
{
  RCC_APB1PeriphClockCmd (RCC_APB1Periph_SPI2, ENABLE);

  GPIO_Conf.GPIO_Pin = radioSDIpin;
  GPIO_Conf.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Conf.GPIO_Speed = GPIO_Speed_10MHz;
  GPIO_Init (GPIOB, &GPIO_Conf);

  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
  SPI_Init (SPI2, &SPI_InitStructure);

  SPI_SSOutputCmd (SPI2, ENABLE);
  SPI_Cmd (SPI2, ENABLE);
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init (SPI2, &SPI_InitStructure);
}
